package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ContentTypeUtil;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileDownloadUtil;

import com.ruoyi.system.domain.Filedata;
import com.ruoyi.system.domain.KnowledgeVo;
import com.ruoyi.system.domain.Permission;
import com.ruoyi.system.mapper.FiledataMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysDeptService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Knowledgepool;
import com.ruoyi.system.service.IKnowledgepoolService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.ruoyi.common.utils.PageUtils.startPage2;

/**
 * knowledgepoolController
 *
 * @author ruoyi
 * @date 2023-08-22
 */
@Controller
@RequestMapping("/system/knowledgepool")
public class KnowledgepoolController extends BaseController {
    private String prefix = "system/knowledgepool";
    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private IKnowledgepoolService knowledgepoolService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private FiledataMapper filedataMapper;

    @RequiresPermissions("system:knowledgepool:view")
    @GetMapping()
    public String knowledgepool() {
        return prefix + "/knowledgepool";
    }


    /**
     * 查询knowledgepool列表
     */
    @DataScope(deptAlias = "k", userAlias = "k")
    @RequiresPermissions("system:knowledgepool:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Knowledgepool knowledgepool) {
        knowledgepool.setCreatTime("");
        knowledgepool.setSex(null);
        extracted(knowledgepool);
        startPage2();
        List<Knowledgepool> list = knowledgepoolService.selectKnowledgepoolList(knowledgepool);
        return getDataTable(list);
    }

    private void extracted(Knowledgepool knowledgepool) {
        SysUser sysUser = ShiroUtils.getSysUser();
        SysDept sysDept = deptMapper.selectDeptById(sysUser.getDeptId());
        if (sysDept.getGrade().equals("3")) {
            List<String> depLS = deptMapper.selectChildrenDeptById(sysDept.getParentId()).stream()
                    .map(a -> String.valueOf(a.getDeptId())).collect(Collectors.toList());
            knowledgepool.setDepIdList(depLS);
        } else if (sysDept.getGrade().equals("2")) {
            List<String> collect = deptMapper.selectChildrenDeptById(sysDept.getParentId()).stream()
                    .map(a -> String.valueOf(a.getDeptId())).collect(Collectors.toList());
            knowledgepool.setDepIdList(collect);
        } else {
            List<String> collect = deptMapper.findAllByGrade(null).stream()
                    .map(a -> String.valueOf(a.getDeptId())).collect(Collectors.toList());
            knowledgepool.setDepIdList(collect);
        }
    }

    @DataScope(deptAlias = "k", userAlias = "k")
    @RequiresPermissions("system:knowledgepool:list")
    @GetMapping("/fileId")
    @ResponseBody
    public List<Filedata> getId(@RequestParam Long kid) {

        return filedataMapper.getId(kid);
    }
    /**
     * 导出knowledgepool列表
     */
    @RequiresPermissions("system:knowledgepool:export")
    @Log(title = "knowledgepool", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult<BaseEntity> export(Knowledgepool knowledgepool) {
        List<Knowledgepool> list = knowledgepoolService.selectKnowledgepoolList(knowledgepool);
        ExcelUtil<Knowledgepool> util = new ExcelUtil<Knowledgepool>(Knowledgepool.class);
        return util.exportExcel(list, "knowledgepool数据");
    }

    /**
     * 新增knowledgepool
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    @GetMapping("/addforsum")
    public String addforsum() {
        return prefix + "/addforsum";
    }


    /**
     * 新增保存knowledgepool
     */
    @RequiresPermissions("system:knowledgepool:add")
    @Log(title = "knowledgepool", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult<BaseEntity> addSave(KnowledgeVo knowledgepool) {
        if (knowledgepool.getType().equals(2L)) {

            if (StringUtils.isEmpty(knowledgepool.getUrls())) {
                return error("文件未上传!");
            }
        }
        return toAjax(knowledgepoolService.insertKnowledgepool(knowledgepool));
    }

    /**
     * 修改knowledgepool
     */
    @RequiresPermissions("system:knowledgepool:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        Knowledgepool knowledgepool = knowledgepoolService.selectKnowledgepoolById(id);
        mmap.put("knowledgepool", knowledgepool);
        return prefix + "/edit";
    }

    /**
     * 修改保存knowledgepool
     */
    @RequiresPermissions("system:knowledgepool:edit")
    @Log(title = "knowledgepool", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult<BaseEntity> editSave(Knowledgepool knowledgepool) {
        return toAjax(knowledgepoolService.updateKnowledgepool(knowledgepool));
    }

    /**
     * 删除knowledgepool
     */
    @RequiresPermissions("system:knowledgepool:remove")
    @Log(title = "knowledgepool", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult<BaseEntity> remove(String ids) {
        return toAjax(knowledgepoolService.deleteKnowledgepoolByIds(ids));
    }


    @RequiresPermissions("system:knowledgepool:download")
    @Log(title = "knowledgepool", businessType = BusinessType.DOWNLOAD)
    @GetMapping("/appendixDownLoad")
    @ResponseBody
//    public void getDownload(@PathVariable("id") String id, HttpServletRequest request, HttpServletResponse response) {
////        Knowledgepool knowledgepool = knowledgepoolService.selectKnowledgepoolByIdForDate(Long.valueOf(id));
////        // Get your file stream from wherever.
////        String fullPath = RuoYiConfig.getUploadPath() + knowledgepool.getFileName().replace("/profile/upload", "");
////        // Replace with the actual directory where your files are stored
////        FileDownloadUtil.downloadFile(response, knowledgepool.getNewFileName(), fullPath);
//    }
    public ResponseEntity<byte[]> getFileData(@RequestParam Long id) {
        Filedata fd = filedataMapper.getFileData1(id);
        String type = fd.getType();

        String mimeType = ContentTypeUtil.MimeType(type);
        MediaType mediaType = MediaType.valueOf(mimeType);
        return ResponseEntity.ok().contentType(mediaType).body(fd.getData());

    }
}